package com.cacho.s2b.lesson.security;

import com.cacho.s2b.lesson.utils.EncryptHelper;
import com.google.gson.Gson;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import java.security.PrivateKey;
import java.util.Date;
import java.util.Map;

public class JwtNimbusJose {
    private static final String ISSUER = "CACHO";
    private static final String AUDIENCE = "CACHO-API";

    public static String nimbusJoseJwt(long timeout, Map<String, String> payload, String privateKey, String... alg) {
        JWSAlgorithm signAlg = JWSAlgorithm.RS256;
        if (alg.length > 0 && alg[0].equalsIgnoreCase("PS256")) {
            signAlg = JWSAlgorithm.PS256;
        }
        // 对body 处理成 json格式
        PrivateKey privateKey0 = new EncryptHelper().StringToPrivateKey(privateKey);
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
        for (Map.Entry<String, String> entry : payload.entrySet()) {
            try {
                Map obj = new Gson().fromJson(entry.getValue(), Map.class);
                builder.claim(entry.getKey(), obj);
            } catch (Exception e) {
                builder.claim(entry.getKey(), entry.getValue());
            }
        }
        JWTClaimsSet claims = builder.issuer("CACHO").
                issueTime(new Date(System.currentTimeMillis())).
                expirationTime(new Date(System.currentTimeMillis() + timeout * 10000)).
                build(); // 30000毫秒=30秒
        // 创建 JWS 头部
        JWSHeader header = new JWSHeader.Builder(signAlg).
                type(JOSEObjectType.JWT).build();
        // 创建签名的JWT
        SignedJWT signedJWT = new SignedJWT(header, claims);
        RSASSASigner signer = new RSASSASigner(privateKey0);
        try {
            signedJWT.sign(signer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将JWT转换为字符串形式
        String jwtString = signedJWT.serialize();
        System.out.println("JWT：" + jwtString);
        return jwtString;
    }
}
